package com.purchasing.system.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import com.purchasing.system.model.Notification;
import com.purchasing.system.payload.response.MessageResponse;
import com.purchasing.system.payload.response.PagedResponse;
import com.purchasing.system.security.services.UserDetailsImpl;
import com.purchasing.system.service.NotificationService;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/notifications")
public class NotificationController {
    @Autowired
    private NotificationService notificationService;

    @GetMapping
    public ResponseEntity<?> getUserNotifications(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Boolean read,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();//通过 SecurityContextHolder 获取当前用户的认证信息；将认证信息转换为 UserDetailsImpl 对象，从中提取用户 ID。
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());//构建分页请求，按创建时间降序排序。
        
        // 处理日期范围
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        
        if (startDate != null && !startDate.isEmpty()) {
            startDateTime = LocalDate.parse(startDate).atStartOfDay();
        }
        
        if (endDate != null && !endDate.isEmpty()) {
            endDateTime = LocalDate.parse(endDate).atTime(LocalTime.MAX);
        }
        
        Page<Notification> notifications;
        
        // 根据参数调用不同的服务方法
        if (type != null || read != null || startDateTime != null || endDateTime != null) {
            notifications = notificationService.getUserNotificationsWithFilters(
                    userDetails.getId(), 
                    type, 
                    read, 
                    startDateTime, 
                    endDateTime, 
                    pageable);
        } else {
            notifications = notificationService.getUserNotifications(userDetails.getId(), pageable);
        }
        
        return ResponseEntity.ok(new PagedResponse<>(
                notifications.getContent(),
                notifications.getNumber(),
                notifications.getSize(),
                notifications.getTotalElements(),
                notifications.getTotalPages(),
                notifications.isLast()
        ));
    }

//    这段代码的整体功能是：
//
//    接收一个HTTP GET请求，路径为/unread。
//    从Spring Security的上下文中获取当前认证用户的信息。
//    从认证信息中提取用户的ID。
//            调用服务层方法notificationService.getUnreadNotifications()，传入用户ID，获取该用户的未读通知列表。
//    将未读通知列表作为HTTP响应返回给客户端，状态码为200（OK）。
    @GetMapping("/unread")
    //ResponseEntity是Spring提供的一个类，用于封装HTTP响应，包括状态码、响应头和响应体。?表示返回的具体类型可以是任意类型，在这里是动态的，由方法内部决定。
    public ResponseEntity<?> getUnreadNotifications() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();//SecurityContextHolder是Spring Security提供的一个工具类，用于存储当前线程的安全上下文（比如当前登录用户的信息）
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();//authentication.getPrincipal()返回当前认证主体的信息，强制转换为自定义的 UserDetailsImpl 类型
        
        List<Notification> unreadNotifications = notificationService.getUnreadNotifications(userDetails.getId());
        
        return ResponseEntity.ok(unreadNotifications);
    }

//    这段代码实现了一个简单而实用的 RESTful 接口，用于统计当前用户的未读通知数量。它的特点是：
//
//            轻量级：只返回一个数字，数据量小，适合频繁调用。
//            安全：依赖于 Spring Security，确保只有认证用户才能访问。
//            易扩展：可以轻松结合前端需求进行功能扩展，比如实时提醒、缓存优化等。
    @GetMapping("/count-unread")
    public ResponseEntity<?> countUnreadNotifications() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        long count = notificationService.countUnreadNotifications(userDetails.getId());//传入当前用户的 ID（userDetails.getId()），统计该用户的未读通知数量。
        
        return ResponseEntity.ok(count);
    }

    @PutMapping("/{id}/read")
    public ResponseEntity<?> markNotificationAsRead(@PathVariable Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //从当前线程的安全上下文中获取当前用户的认证信息，并将其存储在一个 Authentication 类型的变量 authentication 中。
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        //从 Authentication 对象中提取认证的主体（principal），并将其强制转换为自定义的 UserDetailsImpl 类型，存储在变量 userDetails 中。
        
        Notification notification = notificationService.markNotificationAsRead(id, userDetails.getId());
        
        return ResponseEntity.ok(notification);
    }

    @PutMapping("/read-all")

    public ResponseEntity<?> markAllNotificationsAsRead() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        notificationService.markAllNotificationsAsRead(userDetails.getId());
        
        return ResponseEntity.ok(new MessageResponse("All notifications marked as read"));
    }
} 